package com.walker.core;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class DmDatasourceConfig {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DmDatasourceConfig.class);

	@Value("${spring.datasource.druid.datamanage.type}")
	private String dbType;

	@Value("${spring.datasource.druid.datamanage.driver-class-name}")
	private String driverClassName;

	@Value("${spring.datasource.druid.datamanage.url}")
	private String dbUrl;

	@Value("${spring.datasource.druid.datamanage.username}")
	private String username;

	@Value("${spring.datasource.druid.datamanage.password}")
	private String password;

	@Value("${spring.datasource.druid.connection-properties}")
	private String connectionProperties;

	@Bean(name = "datamanageDataSource")
	@Qualifier("datamanageDataSource")
	@Primary
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(dbUrl);
		datasource.setUsername(username);
		datasource.setPassword(password);
		datasource.setDriverClassName(driverClassName);
		datasource.setConnectionProperties(connectionProperties);
		datasource.setDbType(dbType);
		try {
			datasource.setPasswordCallbackClassName("com.walker.util.DbPasswordCallback");
		} catch (Exception e) {
			LOGGER.error("druid configuration initialization passwordCallbackClassName", e);
		}

		try {
			datasource.setFilters("config.enabled=true");
		} catch (SQLException e) {
			LOGGER.error("druid configuration initialization filter", e);
		}
		return datasource;
	}
}